<template>
  <web-view @message="onMessage" class="flex-1" :webview-styles="webviewStyles" :update-title="Boolean(pageTitle)"
    :src="src" />
</template>

<script lang="ts" setup>
import { onLoad, onShareAppMessage } from "@dcloudio/uni-app";
import { isAbsoluteURL } from "@/common/libs/utils";
import { ref } from "vue";

const { COLOR_PRIMARY } = getApp().globalData!.$config;

const webviewStyles = {
  progress: {
    color: COLOR_PRIMARY,
  },
};
const { $config = {} } = getApp().globalData || {};
const pageTitle = ref<string>(""),
  src = ref<string>("");

onLoad(({ url = "", title = "" }: any) => {
  url = decodeURIComponent(url);
  
  src.value = isAbsoluteURL(url) ? url : $config.URL_STATIC + decodeURIComponent(url);

  if (title) {
    pageTitle.value = decodeURIComponent(title);
    uni.setNavigationBarTitle({ title });
    return;
  }
  // #ifdef APP-PLUS
  let pages = getCurrentPages();//获取当前页面栈的实例
  let currentPage: any = pages[pages.length - 1]; // 上一页
  const currentWebview = currentPage.$getAppWebview();

  // 监听当前页面webview对象的title
  setTimeout(() => {
    const wv = currentWebview.children()[0];
    wv.addEventListener('titleUpdate', ({ title }: any) => {
      uni.setNavigationBarTitle({ title });
    }, false)
  }, 200);
  // #endif
});
onShareAppMessage(({ webViewUrl }) => ({
  title: pageTitle.value,
  path: `/pages/common/webview?url=${webViewUrl}`
}));

const onMessage = (e: any) => {
  // console.log(e);
}

</script>